<?php
namespace Admin\Controller;
use Think\Model;

class AreaController extends BaseController {

    public function index() {
        $m = M('district');
        $map['level'] = 1;
        $data = $m->where($map)->select();
        foreach ($data as $k => $v) {
            $map['level'] = 2;
            $map['pid'] = $v['id'];
            $data[ $k ]['city'] = $m->where($map)->select();
            foreach ($data[ $k ]['city'] as $key => $value) {
                $map['level'] = 3;
                $map['pid'] = $value['id'];
                $data[ $k ]['city'][ $key ]['district'] = $m->where($map)->select();
            }
        }
        $this->data = $data;
        $this->data_json = json_encode($data);
        $this->display();
    }

    function dosave() {
        $data = I('post.');
        $id = $data['id'];
        unset($data['id']);
        $Dis = M('District');
        $Dis->startTrans();
        $map = ['id' => $id];
        $d = $Dis->where($map)->find();
        if($d['price_rent']==$data['price_rent'] && $d['price_buy']==$data['price_buy']){
            $j = ['status' => 'error' , 'data' => '数据不变'];
            echo json_encode($j);
            return;
        }
        switch ($d['level']) {
            case 1:
                $r = $Dis->where($map)->data($data)->save();
                if (!$r) {
                    $Dis->rollback();
                    $j = ['status' => 'error' , 'data' => '保存错误,101'];
                    echo json_encode($j);
                    return;
                }
                $map = ['pid' => $d['id']];
            case 2:
                $r = $Dis->where($map)->data($data)->save();
                if (!$r) {
                    $Dis->rollback();
                    $j = ['status' => 'error' , 'data' => '保存错误,102'];
                    echo json_encode($j);

                    return;
                }
                $d = $Dis->where($map)->field('id')->select();
                $pid=[];
                foreach($d as $k=>$v){
                    array_push($pid,$v['id']);
                }
                $map = ['pid' => ['in',implode(',',$pid)]];
            case 3:
                $r = $Dis->where($map)->data($data)->save();
                if (!$r) {
                    $Dis->rollback();
                    $j = ['status' => 'error' , 'data' => '保存错误,103'];
                    echo json_encode($j);
                    return;
                }
                break;
            default:
                break;
        }
        $Dis->commit();
        $j = ['status' => 'success' , 'data' => '保存成功'];
        echo json_encode($j);
        return;
    }

    function getPrice() {
        $id = I('post.id');
        $d = M('District')->where(['id' => $id])->field('price_rent,price_buy')->find();
        if ($d) {
            $j = ['status' => 'success' , 'data' => $d];
        } else {
            $j = ['status' => 'error' , 'data' => '获取失败'];
        }
        echo json_encode($j);
    }
}